#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <PORT>\n", argv[0]);
        exit(1);
    }

    // 创建TCP套接字
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    
    // 绑定地址
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(atoi(argv[1]));
    
    if (bind(server_fd, (struct sockaddr*)&addr, sizeof(addr))) {
        perror("bind failed");
        exit(1);
    }

    // 开始监听
    listen(server_fd, 2);
    printf("Waiting for 2 clients...\n");

    // 接受第一个客户端（F103）
    struct sockaddr_in f103_addr;
    socklen_t addr_len = sizeof(f103_addr);
    int f103_fd = accept(server_fd, (struct sockaddr*)&f103_addr, &addr_len);
    printf("F103 connected: %s\n", inet_ntoa(f103_addr.sin_addr));

    // 接受第二个客户端（6818）
    struct sockaddr_in arm_addr;
    int arm_fd = accept(server_fd, (struct sockaddr*)&arm_addr, &addr_len);
    printf("6818 connected: %s\n", inet_ntoa(arm_addr.sin_addr));

    // 数据转发循环
    char buffer[100];
    while (1) {
        // 从F103接收数据
        int len = read(f103_fd, buffer, 100);
        if (len <= 0) break;

        printf("103:%s",buffer);

        // 转发给6818
        if (write(arm_fd, buffer, len) != len) {
            perror("forward failed");
            break;
        }

        printf("Forwarded: %.*s", (int)len, buffer);
    }

    // 清理资源
    close(f103_fd);
    close(arm_fd);
    close(server_fd);
    return 0;
}